﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;
using Lvzhi.Core;
using Lvzhi.Entities;
using Lvzhi.Entities.BaseEnum;
using Lvzhi.Provide.JsonHelper;
using Lvzhi.Provide.Rpg;
using Webdiyer.WebControls.Mvc;
using Lvzhi.AdminCenter.Extension.MvcHelper;
using Lvzhi.AdminCenter.Models;
using Newtonsoft.Json;

namespace Lvzhi.AdminCenter.Controllers
{
    public class TicketController : BaseController
    {
        private UserCore ucore = new UserCore();
        private UserGrantCore ugcore = new UserGrantCore();
        private TicketCore tcore = new TicketCore();
        private ProductCore pcore = new ProductCore();
        private TicketHistoryCore thcore = new TicketHistoryCore(); 

        /// <summary>
        /// 单证管理,超管看全部，其他的看自己的单证
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(int id = 1, int size = 10, string key = "")
        {
            Expression<Func<Core_Ticket, Boolean>> expr = t => t.T_State == 0;
            var user = GetUser();
            if (!string.IsNullOrWhiteSpace(key))
            {
                expr = expr.And(t => t.T_Name.Contains(key.Trim()));
            }
            if (GetUser().U_Role == 0)  //超管
            {
                var list = tcore.LoadEntities(expr).OrderByDescending(o => o.T_CreateTime).ToPagedList(id, size);
                return View(list);
            }
            else
            {
                var list =
                    thcore.LoadEntities(o => o.H_UserId == user.U_Id && o.H_State == 0)
                        .OrderByDescending(o => o.H_CreateTime).ToList()
                        .Select(o => new Core_Ticket()
                        {
                            T_Id = o.H_ProductId,
                            T_Name = o.H_TicketName,
                            T_ProductName = o.H_ProductName,
                            T_RemainCount = o.H_RemainCount,
                            T_SNo = o.H_SNo,
                            T_ENo = o.H_ENo,
                            T_CurrentNo = o.H_CurrentNo,
                            T_Flag = o.H_Flag,
                            T_Memo = o.H_Id.ToString() //这个地方是个恶心的标识，如果不是超管，就把ID暂存到memo

                        }).ToPagedList(id, size);
                return View(list);
            }
            return null;
        }
        /// <summary>
        /// 添加/编辑单证
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(Guid? id)
        {
            if (GetUser().U_Role != 0)
            {
                throw new Exception("您没有权限");
            }
            Core_Ticket obj = null;
            if (!id.HasValue)
            {
                obj = new Core_Ticket()
                {
                    T_Id = Guid.Empty,
                    T_CreateTime = DateTime.Now
                };
            }
            else
            {
                obj = tcore.LoadEntity(o => o.T_Id == id && o.T_State == 0);// && o.T_Flag == 0
            }
            if (obj == null)
            {
                throw new Exception("数据不存在");
            }
            TempData["ProductList"] = pcore.LoadEntities(o => o.P_State == 0).ToList().Select(v => new SelectListItem
            {
                Text = v.P_Name,
                Value = $"{v.P_Name}|{v.P_Id}",
                Selected = $"{v.P_Name}|{v.P_Id}" == $"{obj.T_ProductName}|{obj.T_ProductId}"
            });

            return View(obj);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Core_Ticket obj)
        {
            if (GetUser().U_Role != 0)
            {
                throw new Exception("您没有权限");
            }
            var product = Request.Form["Product"].Split('|');
            obj.T_UpdateTime = DateTime.Now;
            obj.T_ProductId = Guid.Parse(product[1]);
            obj.T_ProductName = product[0];

            if (obj.T_Id == Guid.Empty)
            {
                obj.T_Id = Guid.NewGuid();

                tcore.AddEntity(obj);
            }
            else
            {
                tcore.UpdateEntity(obj);
            }
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 单证领用
        /// </summary>
        /// <returns></returns>
        public ActionResult Receive(int id = 1, int size = 10, string key = "")
        {
            var user = GetUser();
            Expression<Func<Core_TicketHistory, Boolean>> expr = t => t.H_UserId == user.U_Id;  //当前用户的单证



            if (!string.IsNullOrWhiteSpace(key))
            {
                expr = expr.And(t => t.H_TicketName.Contains(key.Trim()));
            }
            var list = thcore.LoadEntities(expr).OrderByDescending(o => o.H_CreateTime).ToPagedList(id, size);
            return View(list);
        }

        /// <summary>
        /// 领用单证
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string Receive(Guid id)
        {
            var user = GetUser();
            var info = thcore.LoadEntity(o => o.H_Id == id && o.H_State == (int)TicketHistoryStatusEnum.未领用 && o.H_Flag == 0 && o.H_UserId == user.U_Id);

            if (info != null)
            {

                info.H_State= (int)TicketHistoryStatusEnum.正常;
                info.H_ReciveTime = DateTime.Now;
                if (thcore.UpdateEntity(info)) //更改状态
                {
                    return "ok";
                }

            }
            return "更新数据失败";
        }

        /// <summary>
        /// 单证发放（只能发给代理商，代理商再发给下面的用户）
        /// </summary>
        /// <returns></returns>
        public ActionResult Send(Guid id, string memo = "")
        {
            var user = GetUser();
            Core_Ticket info = null;

            if (user.U_Role == 0)//超管直接改ticket
            {

                info = tcore.LoadEntity(o => o.T_Id == id && o.T_State == 0 && o.T_Flag == 0);
            }
            else if (Guid.TryParse(memo, out id))
            {

                var th = thcore.LoadEntity(o => o.H_TicketId == id && o.H_UserId == user.U_Id);
                info = new Core_Ticket()
                {
                    T_Id = th.H_TicketId,
                    T_Count = th.H_Count,
                    T_RemainCount = th.H_RemainCount,
                    T_ProductId = th.H_ProductId,
                    T_ProductName = th.H_ProductName,
                    T_Name = th.H_TicketName,
                    T_SNo = th.H_SNo,
                    T_ENo = th.H_ENo,
                    T_CurrentNo = th.H_CurrentNo,
                    T_Memo = th.H_Id.ToString()
                };
            }

            TempData["UserList"] = ucore.LoadEntities(o => o.U_PId == user.U_Id && o.U_State == 0).ToList().Select(v => new SelectListItem
            {
                Text = v.U_Name,
                Value = v.U_Id.ToString(),
                //Selected = $"{v.P_Name}|{v.P_Id}" == $"{obj.T_ProductName}|{obj.T_ProductId}"
            });
            return View(info);
        }
        /// <summary>
        /// 发放单证
        /// </summary>
        /// <param name="id"></param>
        /// <param name="memo"></param>
        /// <param name="count"></param>
        /// <param name="uname"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpPost]
        public string Send(Guid id, string memo, int count, int uid)
        {

            var  curuser = GetUser();
            var user = ucore.LoadEntity(o => o.U_Id == uid && o.U_State == 0 && o.U_PId == curuser.U_Id);

            if (user == null)
            {
                return "用户不存在";
            }
            if (GetUser().U_Role != 0 && Guid.TryParse(memo, out id))  //不是超管就，修改自己的那份儿
            {
                var info = thcore.LoadEntity(o => o.H_Id == id && GetUser().U_Id == o.H_UserId && o.H_State == (int)TicketHistoryStatusEnum.正常 && o.H_Flag == 0);


                if (info != null)
                {
                    if (info.H_RemainCount < count)
                    {
                        return "发放数量过多，剩余次数不足";
                    }


                    Core_TicketHistory th = new Core_TicketHistory()
                    {
                        H_Id = Guid.NewGuid(),
                        H_Count = count,
                        H_State = (int)TicketHistoryStatusEnum.未领用,//2表示未领用
                        H_CreateTime = DateTime.Now,
                        H_SNo = info.H_CurrentNo,
                        H_ENo = info.H_CurrentNo + count,
                        H_Flag = 0,
                        H_CurrentNo = info.H_CurrentNo,
                        H_Memo = "",
                        H_ProductId = info.H_ProductId,
                        H_ProductName = info.H_ProductName,
                        H_RemainCount = count,
                        H_TicketId = info.H_TicketId,
                        H_TicketName = info.H_TicketName,
                        H_UserId = user.U_Id,
                        H_UserName = user.U_Name,

                        H_FromUId = curuser.U_Id,
                        H_FromUName = curuser.U_Name
                    };

                    thcore.AddEntity(th);


                    info.H_RemainCount -= count;
                    info.H_CurrentNo += count;

                    if (thcore.UpdateEntity(info)) //更改状态
                    {
                        return "ok";
                    }
                }
                else
                {
                    return "单证不存在";
                }


            }
            else
            {
                //超管修改

                var info = tcore.LoadEntity(o => o.T_Id == id && o.T_State == 0 && o.T_Flag == 0);

                if (info != null)
                {

                    Core_TicketHistory th = new Core_TicketHistory()
                    {
                        H_Id = Guid.NewGuid(),
                        H_Count = count,
                        H_State = (int)TicketHistoryStatusEnum.未领用,//2表示未领用
                        H_CreateTime = DateTime.Now,
                        H_SNo = info.T_CurrentNo,
                        H_ENo = info.T_CurrentNo + count,
                        H_Flag = 0,
                        H_CurrentNo = info.T_CurrentNo,
                        H_Memo = "",
                        H_ProductId = info.T_ProductId,
                        H_ProductName = info.T_ProductName,
                        H_RemainCount = count,
                        H_TicketId = info.T_Id,
                        H_TicketName = info.T_Name,
                        H_UserId = user.U_Id,
                        H_UserName = user.U_Name,


                        H_FromUId = curuser.U_Id,
                        H_FromUName = curuser.U_Name
                    };

                    thcore.AddEntity(th);

                    info.T_CurrentNo += count;
                    info.T_RemainCount -= count;

                    if (tcore.UpdateEntity(info)) //更改状态
                    {
                        return "ok";
                    }
                }
                else
                {
                    return "数据不存在2";
                }
            }
            return "更新数据失败";
        }


        /// <summary>
        /// 单证发放历史
        /// </summary>
        /// <returns></returns>
        public ActionResult SendLog(int id = 1, int size = 10, string key = "")
        {

            var user = GetUser();
            Expression<Func<Core_TicketHistory, Boolean>> expr = t => t.H_FromUId == user.U_Id;
            if (GetUser().U_Role != 0)
            {
                expr = expr.And(t => t.H_UserId == user.U_Id);
            }

            if (!string.IsNullOrWhiteSpace(key))
            {
                expr = expr.And(t => t.H_UserName.Contains(key.Trim()));
            }
            var list = thcore.LoadEntities(expr).OrderByDescending(o => o.H_CreateTime).ToPagedList(id, size);
            return View(list);
        }
        /// <summary>
        /// 过期申退
        /// </summary>
        /// <returns></returns>
        public ActionResult OuttimeBack()
        {
            return View();
        }
        /// <summary>
        /// 票号分配
        /// </summary>
        /// <returns></returns>
        public ActionResult Allot(int id)
        {

            int pid = GetUser().U_Id;
            var user = ucore.LoadEntity(o => o.U_Id == id && o.U_State == 0 && o.U_PId == pid);
            if (user == null)
            {
                TempData["Msg"] = "用户不存在，或者您没有分配此用户的权限";
                return RedirectToAction("Index","Error");
                throw new Exception("用户不存在，或者您没有分配此用户的权限");
            }

            ViewBag.Agent = GetUser();
            ViewBag.User = user;
            return View();
        }
        /// <summary>
        /// 分配次数
        /// </summary>
        /// <param name="uinterface"></param>
        /// <param name="uinvoice"></param>
        /// <param name="uid"></param>
        /// <param name="memo"></param>
        /// <returns></returns>
        [HttpPost]
        public string Allot(int uinterface, int uinvoice, int uid, string memo)
        {
            Core_User agent = GetUser();
            int pid = agent.U_Id;
            var user = ucore.LoadEntity(o => o.U_Id == uid && o.U_State == 0 && o.U_PId == pid);
            if (user == null)
            {
                return ("用户不存在，或者您没有分配此用户的权限");
            }
            if (agent.U_InvoiceCount < uinvoice)
            {
                return "分配发票次数不足";
            }

            if (agent.U_InterfaceCount < uinterface)
            {
                return "分配票号次数不足";
            }

            agent.U_InterfaceCount -= uinterface;
            agent.U_InvoiceCount -= uinvoice;

            var rs1 = ucore.UpdateEntity(agent);
            if (rs1)
            {
                user.U_InterfaceCount += uinterface;
                user.U_InvoiceCount += uinvoice;

                var rs2 = ucore.UpdateEntity(user);

                CookieHelper.SetCookie("manager", JsonSerialize.Instance.ObjectToJson(agent), DateTime.Now.AddSeconds(30));
                if (rs2)
                {
                    Core_UserGrant obj = new Core_UserGrant()
                    {
                        UG_FromUId = agent.U_Id,
                        UG_Flag = 0,
                        UG_FromUName = agent.U_Name,
                        UG_InterfaceCount = uinterface,
                        UG_InvoiceCount = uinvoice,
                        UG_Memo = memo,
                        UG_State = 0,
                        UG_Time = DateTime.Now,
                        UG_ToUId = user.U_Id,
                        UG_ToUName = user.U_Name
                    };

                    ugcore.AddEntity(obj);
                    return "分配成功";
                }
            }

            return "分配错误";
        }


        /// <summary>
        /// 使用/取消单证
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string Option(Guid id, string memo = "")
        {
            var user = GetUser();
            if (user.U_Role != 0 && Guid.TryParse(memo, out id))  //不是超管就，修改自己的那份儿
            {
                var info = thcore.LoadEntity(o => o.H_Id == id && user.U_Id == o.H_UserId);

                if (info != null)
                {
                    var state = info.H_Flag;


                    if (state == (int)UserStatusEnum.冻结)
                    {
                        state = (int)UserStatusEnum.正常;
                    }
                    else if (state == (int)UserStatusEnum.正常)
                    {
                        state = (int)UserStatusEnum.冻结;
                    }
                    info.H_Flag = state;
                    if (thcore.UpdateEntity(info)) //更改状态
                    {
                        return "ok";
                    }
                }


            }
            else
            {
                //超管修改

                var info = tcore.LoadEntity(o => o.T_Id == id );//&& o.T_State == 0 && o.T_Flag == 0

                if (info != null)
                {
                    var state = info.T_Flag;


                    if (state == (int)UserStatusEnum.冻结)
                    {
                        state = (int)UserStatusEnum.正常;
                    }
                    else if (state == (int)UserStatusEnum.正常)
                    {
                        state = (int)UserStatusEnum.冻结;
                    }
                    info.T_Flag = state;
                    if (tcore.UpdateEntity(info)) //更改状态
                    {
                        return "ok";
                    }
                }
            }
            return "更新数据失败";
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string Remove(Guid id)
        {
            if (GetUser().U_Role != 0)
            {
                throw new Exception("您没有权限");
            }
            var info = tcore.LoadEntity(o => o.T_Id == id && o.T_State == 0 && o.T_Flag == 0);

            if (info != null)
            {

                info.T_State = 1;

                if (tcore.UpdateEntity(info)) //更改状态
                {
                    return "ok";
                }

            }
            return "更新数据失败";
        }

        /// <summary>
        /// 单证 +1
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public string AddOne(Guid id)
        {
            var info = tcore.LoadEntity(o => o.T_Id == id && o.T_State == 0 && o.T_Flag == 0);

            if (info != null)
            {
                info.T_RemainCount -= 1;// 剩余次数 -1

                if (tcore.UpdateEntity(info)) //更改状态
                {
                    Sys_OperateLog log = new Sys_OperateLog()
                    {
                        L_Desc = "",
                        L_DriverType = 0,
                        L_Flag = (int)LogTypeEnum.单证加一,
                        L_Phone = GetUser().U_Phone,
                        L_Status = 0,
                        L_Time = DateTime.Now,
                        L_UId = GetUser().U_Id.ToString(),
                    };
                    new OperateLogCore().AddEntity(log);
                    return "ok";
                }

            }
            return "更新数据失败";
        }
    }
}